package com.lagou.edu.utils;


import com.lagou.edu.anno.Componment;

import java.sql.Connection;
import java.sql.SQLException;

@Componment(value = "DruidConnUtils")
public class ConnectionUtils {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

//    private ConnectionUtils(){
//
//    }
//
//    private volatile static ConnectionUtils connectionUtils = null;
//
//    /**
//     * 双重校验锁获取实例对象
//     * @return
//     */
//    public static ConnectionUtils getInstance() {
//        if(connectionUtils == null) {
//            synchronized (ConnectionUtils.class) {
//                if(connectionUtils == null) {
//                    connectionUtils = new ConnectionUtils();
//                }
//
//            }
//        }
//        return connectionUtils;
//    }

    /**
     * 获取线程绑定的Connection
     * @return
     * @throws SQLException
     */
    public Connection getThreadConn() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection == null) {
            //当前线程尚未绑定数据连接对象，直接获取Connection对象，并且与当前线程绑定
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

}
